//
//  MKUITabBarItemFlowContainer.m
//  MKUI
//
//  Created by 苏尚进 on 2023/10/23.
//  Copyright © 2023 moon. All rights reserved.
//

#import "MKUITabBarItemFlowContainer.h"
#import "MKUITabBarController.h"
#import "UIColor+MKUI.h"
@interface MKUITabBarItemFlowContainer()<MKUItemFlowCollectionViewDelegate>
@property(nonatomic,strong) MKUItemFlowCollectionView *flowColletionView;
@end

@implementation MKUITabBarItemFlowContainer
- (id)initWithFrame:(CGRect)frame{
    if(self=[super initWithFrame:frame]){
        self.flowColletionView = [[MKUItemFlowCollectionView alloc] init];
        self.flowColletionView.delegate = self;
        self.itemCollectionCellClass = MKUITabBarItemFlowCellView.class;
        self.separatorColor = UIColor.mk_listViewSeparatorColor;
        [self addSubview:self.flowColletionView];
    }
    return self;
}
- (void)layoutSubviews{
    [super layoutSubviews];
    CGRect bounds = self.bounds;
    self.flowColletionView.frame = bounds;
}
- (CGSize)sizeThatFits:(CGSize)size{
    CGSize s = [self.flowColletionView sizeThatFits:size];
    return s;
}
- (void)setItemCollectionCellClass:(Class)itemCollectionCellClass{
    self.flowColletionView.itemCellClass = itemCollectionCellClass;
}
- (Class)itemCollectionCellClass{
    return self.flowColletionView.itemCellClass;
}
- (void)setSeparatorViewClass:(Class)separatorViewClass{
    self.flowColletionView.separatorViewClass = separatorViewClass;
}
- (Class)separatorViewClass{
    return self.flowColletionView.separatorViewClass;
}
- (void)setSeparatorColor:(UIColor *)separatorColor{
    self.flowColletionView.separatorColor = separatorColor;
}
- (UIColor *)separatorColor{
    return self.flowColletionView.separatorColor;
}
- (void)setSeparatorSize:(CGSize)separatorSize{
    self.flowColletionView.separatorSize = separatorSize;
}
- (CGSize)separatorSize{
    return self.flowColletionView.separatorSize;
}
- (void)setItemIndicatorViewClass:(Class)itemIndicatorViewClass{
    self.flowColletionView.itemIndicatorViewClass = itemIndicatorViewClass;
}
- (Class)itemIndicatorViewClass{
    return self.flowColletionView.itemIndicatorViewClass;
}
- (UIView *)itemIndicatorView{
    return self.flowColletionView.itemIndicatorView;
}

//响应content滚动容器的滚动事件
- (void)didScrollFromIndex:(NSInteger)fromIndex to:(NSInteger)toIndex withProgress:(CGFloat)progress{
    [self.flowColletionView scrollItemIndicatorViewFromIndex:fromIndex to:toIndex withProgress:progress];
    [self.flowColletionView collectionViewScrollItemFromIndex:fromIndex to:toIndex withProgress:progress];
}
//content容器是否能滚动切换内容
- (BOOL)contentContainerCanScrollContent{
    return YES;
}
//刷新UI，并显示动画效果
- (void)reloadDataWithAnimated:(BOOL)animated{
    [super reloadDataWithAnimated:animated];
    self.flowColletionView.items = self.items;
    self.flowColletionView.selectedIndex = self.selectedIndex;
    [self.flowColletionView reloadDataWithAnimated:animated];
}

#pragma mark - delegate:MKUItemFlowCollectionViewDelegate
- (CGSize)itemFlowCollectionView:(MKUItemFlowCollectionView *)view itemSizeAtIndex:(NSInteger)index collectionCellModel:(MKUICollectionViewCellModel *)cellModel{
    if([self.delegate respondsToSelector:@selector(tabBarItemFlowContainer:itemSizeAtIndex:collectionCellModel:)]){
        return [self.delegate tabBarItemFlowContainer:self itemSizeAtIndex:index collectionCellModel:cellModel];
    }
    Class cellClass = cellModel.cellClass;
    if([cellClass respondsToSelector:@selector(sizeWithCollectionView:collectionCellModel:)]){
        CGSize size = [cellClass sizeWithCollectionView:view.collectionView collectionCellModel:cellModel];
        return size;
    }
    return CGSizeZero;
}
- (Class)itemFlowCollectionView:(MKUItemFlowCollectionView *)view itemCellClassAtIndex:(NSInteger)index{
    if([self.delegate respondsToSelector:@selector(tabBarItemFlowContainer:itemCellClassAtIndex:)]){
        return [self.delegate tabBarItemFlowContainer:self itemCellClassAtIndex:index];
    }
    __kindof UITabBarItem *item = self.items[index];
    if([item isKindOfClass:MKUICustomTabBarItem.class]){
        MKUICustomTabBarItem *customItem = item;
        if(customItem.itemCellClass){
            return customItem.itemCellClass;
        }
    }
    return self.itemCollectionCellClass;
}
- (void)itemFlowCollectionView:(MKUItemFlowCollectionView *)view didSelectIndex:(NSInteger)selectedIndex{
    [self setSelectedIndex:selectedIndex animated:YES];
    [self.tabBarController itemContainerDidSelectIndex:selectedIndex animated:YES];
    if([self.delegate respondsToSelector:@selector(tabBarItemFlowContainer:didSelectIndex:)]){
        [self.delegate tabBarItemFlowContainer:self didSelectIndex:selectedIndex];
    }
}
- (CGSize)separatorSizeOfItemFlowCollectionView:(MKUItemFlowCollectionView *)view{
    if([self.delegate respondsToSelector:@selector(separatorSizeOfTabBarItemFlowContainer:)]){
        return [self.delegate separatorSizeOfTabBarItemFlowContainer:self];
    }
    return view.separatorSize;
}
@end

#import "UIColor+MKUI.h"
#import "UIImageView+MKUI.h"
#import "NSObject+MKUI.h"
@interface MKUITabBarItemFlowCellView()
@property(nonatomic,strong) MKUIFlowLayoutButton *tabBarItemButton;
@property(nonatomic,strong) MKUICustomTabBarItemBadgeView *badgeView;//图片右上角的角标视图
@end
@implementation MKUITabBarItemFlowCellView
#ifdef DEBUG
- (void)setFrame:(CGRect)frame{
    [super setFrame:frame];
}
#endif
#ifdef DEBUG
- (void)dealloc{
    
}
#endif
- (id)initWithFrame:(CGRect)frame{
    if(self=[super initWithFrame:frame]){
        self.titleLabel.hidden = YES;
        self.tabBarItemButton = [[MKUIFlowLayoutButton alloc] initWithContentStyle:MKUIFlowLayoutButtonContentStyleHorizontal];
        [self.tabBarItemButton setTitleColor:[self.class titleColorWithSelected:NO] forState:UIControlStateNormal];
        [self.tabBarItemButton setTitleColor:[self.class titleColorWithSelected:YES] forState:UIControlStateSelected];
        [self.tabBarItemButton setTitleColor:[self.class titleColorWithSelected:YES].mk_halfColor forState:UIControlStateHighlighted];
        self.tabBarItemButton.contentInsets = UIEdgeInsetsMake(10, 10, 10, 10);
        self.tabBarItemButton.imageSize = CGSizeMake(35, 23);
        self.tabBarItemButton.hideImageViewForNoImage = YES;
        self.tabBarItemButton.interitemSpacing = 5;
        [self.tabBarItemButton addTarget:self action:@selector(__onTabBarItemButtonDidTap:) forControlEvents:UIControlEventTouchUpInside];
        [self.contentView addSubview:self.tabBarItemButton];
        //
        self.badgeView = [[MKUICustomTabBarItemBadgeView alloc] init];
        [self.contentView addSubview:self.badgeView];
    }
    return self;
}
+ (UIColor *)titleColorWithSelected:(BOOL)selected{
    return selected?[UIColor systemBlueColor]:[UIColor mk_colorWithLight:[UIColor blackColor] dark:[UIColor whiteColor]];
}
- (void)__onTabBarItemButtonDidTap:(id)sender{
    [self.collectionCellModel didClickSelf];
}
- (void)customLayoutSubviews{
    [super customLayoutSubviews];
    CGRect bounds = self.contentView.bounds;
    UIEdgeInsets safeAreaInsets = UIEdgeInsetsZero;
    if (@available(iOS 11.0, *)) {
        safeAreaInsets = self.safeAreaInsets;
    }
    CGRect f1 = bounds;
    f1.size.height -= safeAreaInsets.bottom;
    self.tabBarItemButton.frame = f1;
    //由于badge的布局会依赖itemButton，当itemButton的frame没有变更，但数据变更时，会导致itemButton的imageView尺寸变更，因此要强制重新布局一次button的内部视图
    [self.tabBarItemButton setNeedsLayout];
    [self.tabBarItemButton layoutIfNeeded];
    
    if(!self.badgeView.hidden){
        CGRect f1 = bounds;
        f1.size = [self.badgeView sizeThatFits:bounds.size];
        CGRect alignFrame = self.tabBarItemButton.frame;
        if(self.tabBarItemButton.contentStyle==MKUIFlowLayoutButtonContentStyleVertical){
            if(self.tabBarItemButton.reverseContent){
                alignFrame = [self.tabBarItemButton convertRect:self.tabBarItemButton.titleLabel.frame toView:self.contentView];
            }else{
                alignFrame = [self.tabBarItemButton.imageView convertRect:self.tabBarItemButton.imageView.mk_frameOfImageContent toView:self.contentView];
            }
        }else{
            if(self.tabBarItemButton.reverseContent){
                alignFrame = [self.tabBarItemButton.imageView convertRect:self.tabBarItemButton.imageView.mk_frameOfImageContent toView:self.contentView];
            }else{
                alignFrame = [self.tabBarItemButton convertRect:self.tabBarItemButton.titleLabel.frame toView:self.contentView];
            }
        }
        if(CGSizeEqualToSize(CGSizeZero, alignFrame.size)){
            alignFrame = self.tabBarItemButton.frame;
        }
        
        MKCGRectSetMidX(&f1, CGRectGetMaxX(alignFrame));
        MKCGRectSetMidY(&f1, CGRectGetMinY(alignFrame));
        f1.origin.y = MAX(1,f1.origin.y);
        f1.origin.x = MIN(f1.origin.x,CGRectGetMaxX(bounds)-f1.size.width-1);
        self.badgeView.frame = f1;
    }
}
- (void)reloadData{
    [self.tabBarItemButton setTitleColor:[self.class titleColorWithSelected:YES] forState:UIControlStateSelected];
    [self.tabBarItemButton setTitleColor:[self.class titleColorWithSelected:NO] forState:UIControlStateNormal];
    __kindof UITabBarItem *item = self.tabBarItem;
    [self.tabBarItemButton setTitle:item.title forState:UIControlStateNormal];
    [self.tabBarItemButton setImage:item.image forState:UIControlStateNormal];
    [self.tabBarItemButton setImage:item.selectedImage forState:UIControlStateSelected];
    self.tabBarItemButton.enabled = item.enabled;
    self.tabBarItemButton.selected = self.collectionCellModel.selected;
    
    self.badgeView.badgeValue = item.badgeValue;
    if([item isKindOfClass:MKUICustomTabBarItem.class]){
        MKUICustomTabBarItem *customItem = item;
        customItem.itemCell = self;
        self.badgeView.badgeStyle = customItem.badgeStyle;
    }
    self.badgeView.hidden = self.badgeView.badgeValue.length==0;
}
- (void)customReloadCellModel{
    [super customReloadCellModel];
    [self reloadData];
}
- (UIView *)itemIndicatorRectView{
    return self.tabBarItemButton;
}
- (CGSize)customSizeThatFits:(CGSize)size{
    CGSize s = [self.tabBarItemButton sizeThatFits:CGSizeMake(99999999, 99999999)];
    s.width = MIN(size.width,s.width);
    s.height = MAX(44,s.height);
    return s;
}
- (UITabBarItem *)tabBarItem{
    if(![self.collectionCellModel.modelValue isKindOfClass:UITabBarItem.class]) return nil;
    return self.collectionCellModel.modelValue;
}
MKDEF_SINGLETON(MKUItemFlowCellView)
- (void)changeColorForItemFlowCollectionView:(MKUItemFlowCollectionView *)view didScrollFromIndex:(NSInteger)fromIndex to:(NSInteger)toIndex progress:(CGFloat)progress{
//    NSLog(@"changeColorForItemFlowCollectionView,from:%@,to:%@",@(fromIndex),@(toIndex));
    NSIndexPath *fromIndexPath = [view cellIndexPathForItemIndex:fromIndex];
    NSIndexPath *toIndexPath = [view cellIndexPathForItemIndex:toIndex];
    NSIndexPath *myIndexPath = self.collectionCellModel.indexPathInModel;
    if(![myIndexPath isEqual:fromIndexPath]&&![myIndexPath isEqual:toIndexPath]){//中间单元格
        [self.tabBarItemButton setTitleColor:[self.class titleColorWithSelected:YES] forState:(UIControlStateSelected)];
        [self.tabBarItemButton setTitleColor:[self.class titleColorWithSelected:NO] forState:(UIControlStateNormal)];
        return;
    }
    
    //颜色渐变
    UIColor *color1;
    UIColor *color2;
    if([myIndexPath isEqual:fromIndexPath]){//选中->未选中
        color1 = [self.class titleColorWithSelected:YES];
        color2 = [self.class titleColorWithSelected:NO];
    }else{//未选中->选中
        color1 = [self.class titleColorWithSelected:NO];
        color2 = [self.class titleColorWithSelected:YES];
    }
    if(color1 && color2){
        UIColor *textColor = MKUIColorInterpolate(color1, color2, progress);
        if(self.tabBarItemButton.selected){
            [self.tabBarItemButton setTitleColor:textColor forState:(UIControlStateSelected)];
        }else{
            [self.tabBarItemButton setTitleColor:textColor forState:(UIControlStateNormal)];
        }
    }
}
- (void)itemFlowCollectionView:(MKUItemFlowCollectionView *)view didScrollFromIndex:(NSInteger)fromIndex to:(NSInteger)toIndex progress:(CGFloat)progress{
    [self changeColorForItemFlowCollectionView:view didScrollFromIndex:fromIndex to:toIndex progress:progress];
}
@end
@implementation MKUITabBarController (MKUITabBarItemFlowContainer)
- (MKUITabBarItemFlowContainer *)itemFlowContainer{
    if([self.itemContainer isKindOfClass:[MKUITabBarItemFlowContainer class]]){
        return self.itemContainer;
    }
    return nil;
}
@end

@implementation MKUITabBarItemFlowContainer(MKUItemFlowIndicatorLineView)
- (MKUItemFlowIndicatorLineView *)itemIndicatorLineView{
    return [self.itemIndicatorView isKindOfClass:MKUItemFlowIndicatorLineView.class]?self.itemIndicatorView:nil;
}
@end
